import request from 'axios'
import { AUTH_TOKEN } from '@/config/token-const'

const service = request.create({
  baseUrl: '/',
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
  timeout: 60000, // 请求超时时间
})

// 获取填充数据
export async function fetchData(config) {
  const { data } = await service(config)
  if (data.code === '00' || data.code === '200') {
    return data.data
  } else if (data.code === '416') {
    return data
  } else {
    throw new Error(data.message || data.msg)
  }
}

/**
 * request interceptor
 */
service.interceptors.request.use(
  async config => {
    // if (token.value && token.value !== 'undefined') {
    //   config.headers.Authorization = 'Bearer ' + token.value // 让每个请求携带自定义 token 请根据实际情况自行修改
    // }
    const authToken = localStorage.getItem(AUTH_TOKEN)
    if (authToken && authToken !== 'undefined') {
      config.headers.Authorization = 'Bearer ' + authToken // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    if (error.response) {
      const data = error.response.data
      console.error('响应错误', data)
    }
    return Promise.reject(error)
  },
)

/**
 * response interceptor
 */
service.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 401:
        // store.dispatch('user/clearToken')
        // error.message = error.response.data.message || '401认证无效'
        // error.statusCode = 401
        // router.push({ name: 'Login' })
      }
    }
    return Promise.reject(error)
  },
)

export default service
